import { createApp } from 'vue';
import ImportComponent from './import.vue';
import api from '@/api/api';
import maps from '@/utils/maps';
import { testData } from './testData';
import elementInstallPlugin from '@/plugin/element';

const titleMap = {
  5: '更新学生',
  6: '更新教师'
}

let instance = null;
let container = null;

export default {
  install(app, { store }) {
    const createImport = () => {
      if (!instance) {
        container = document.createElement('div');
        document.body.appendChild(container);
        const appInstance = createApp(ImportComponent);
        // 注册 Element UI 组件和指令
        appInstance.use(elementInstallPlugin);
        // 配置全局属性，确保组件可以访问 $maps 和 $api
        appInstance.config.globalProperties.$maps = maps;
        appInstance.config.globalProperties.$api = api;
        instance = appInstance.mount(container);
        instance.__store = store;
      }
      return instance;
    };
    const importExcel = (
      schoolId,
      type,
      successCallback,
      failCallback = () => {}
    ) => {
      const importInstance = createImport();
      if (importInstance.visible) return;
      // 一些初始化操作
      const { importType, previewTabs } = maps;
      importInstance.type = type;


      let preivewApi = async () => {};
      let confirmApi = async () => {};
      switch (type) {
        case importType.SCHOOL:
          preivewApi = api.importSchoolPreview;
          confirmApi = api.importSchoolConfirm;
          importInstance.tabs = previewTabs.filter((e) =>
            [1, 2, 3, 4, 0, 5, 6, 7, 9].includes(e.id)
          );
          break;
        case importType.STUDENT:
          preivewApi = api.importStudentPreview;
          confirmApi = api.importStudentConfirm;
          importInstance.tabs = previewTabs.filter((e) => [5, 6, 7].includes(e.id));
          break;
        case importType.UPDATE_STUDENT:
          preivewApi = api.updateStudentPreview;
          confirmApi = api.updateStudentConfirm;
          importInstance.tabs = previewTabs.filter((e) => [6, 7].includes(e.id));
          break;
        case importType.TEACHER:
          preivewApi = api.importTeacherPreview;
          confirmApi = api.importTeacherConfirm;
          importInstance.tabs = previewTabs.filter((e) =>
            [3, 4, 0, 7].includes(e.id)
          );
          break;
        case importType.UPDATE_TEACHER:
          preivewApi = api.importTeacherPreview;
          confirmApi = api.importTeacherConfirm;
          importInstance.tabs = previewTabs.filter((e) =>
            [3, 4, 0, 7].includes(e.id)
          );
          break;
        case importType.USER:
          preivewApi = api.importUserPreview;
          confirmApi = api.importUserConfirm;
          importInstance.tabs = previewTabs.filter((e) => [3, 4, 9].includes(e.id));
          break;
        default:
          // do nothing
          break;
      }
      importInstance.tab = importInstance.tabs[0];
      importInstance.visible = true;
      importInstance.step = 1;
      importInstance.showEmptyPhoneTip = false;
      // 测试操作
      // importInstance.previewData = testData;
      // console.log(importInstance.previewData);
      // importInstance.step = 2;


      importInstance.title = titleMap[importInstance.type] || '导入Excel文件';
      importInstance.schoolId = schoolId;

      importInstance.confirm = async () => {
        if (importInstance.step === 1) {
          // 上传文件阶段
          importInstance.excelFile = importInstance.inputFile.files[0];
          console.log(importInstance.excelFile);
          if (importInstance.excelFile === undefined) {
            importInstance.title = '未上传Excel文件, 请上传文件';
            return;
          }
          const formData = new FormData();
          formData.append('F_school_id', importInstance.schoolId);
          formData.append('excel', importInstance.excelFile);
          if(importInstance.showEmptyPhoneTip) {
            formData.append('F_is_empty_flag', 1);  // 用户确认过，存在电话号码为空，继续导入将生成虚拟号码补充
            importInstance.errorInfoList = [];
            importInstance.errorMsg = '';
          }
          importInstance.title = 'Excel文件解析中....';
          importInstance.errorMsg = '';
          importInstance.loading = true;
          try {
            const { F_responseMsg, F_err_msg, F_responseNo, F_result, empty_phone_err_msg, new_phone_data } =
              await preivewApi(formData);
            if (F_responseNo === 10000) {
              importInstance.step = 2;
              importInstance.previewData = F_result;
              importInstance.new_phone_data = new_phone_data;
            } else {
              importInstance.title = `解析文件失败`;
              if(Array.isArray(empty_phone_err_msg) && empty_phone_err_msg.length > 0) {
                importInstance.showEmptyPhoneTip = true;
                importInstance.errorInfoList = empty_phone_err_msg;
              } else if(F_err_msg && F_err_msg.length){
                importInstance.showEmptyPhoneTip = false;
                importInstance.errorInfoList = F_err_msg;
              } else {
                importInstance.showEmptyPhoneTip = false;
                importInstance.errorMsg = F_responseMsg;
              }
            }
          } catch (err) {
            console.error(err);
            importInstance.title = '解析文件失败';
          }
          importInstance.loading = false;
        } else {
          // 预览阶段
          importInstance.errorMsg = '';
          importInstance.errorInfoList = [];
          const formData = new FormData();
          formData.append('F_school_id', importInstance.schoolId);
          formData.append('excel', importInstance.excelFile);
          if(importInstance.new_phone_data) {
            formData.append('new_phone_data', JSON.stringify(importInstance.new_phone_data));
          }
          importInstance.title = 'Excel文件上传中....';
          importInstance.loading = true;
          try {
            const res = await confirmApi(formData);
            const { F_responseMsg, F_responseNo, F_result, F_err_msg } = res;
            if (F_responseNo === 10000) {
              successCallback(res);
              exit();
            } else {
              if(F_err_msg) {
                importInstance.step2Title = F_err_msg;
              } else {
                importInstance.step2Title = `数据添加失败,${F_responseMsg}`;
              }
            }
          } catch (err) {
            console.error(err);
            importInstance.title = '数据添加失败';
          }
          importInstance.loading = false;
        }
      };
      importInstance.cancel = () => {
        importInstance.teachingColumnList = [];
        importInstance.teachingInfoList = [];
        importInstance.gradeSubjectColumnList = [];
        importInstance.gradeSubjectInfoList = [];

        if (importInstance.step === 1) exit();
        else {
          importInstance.step = 1;
          importInstance.title = titleMap[importInstance.type] || '导入Excel文件';
          importInstance.showEmptyPhoneTip = false;
          importInstance.step2Title = '导入结果预览';
        }
      };
      const exit = () => {
        importInstance.errorMsg = '';
        importInstance.errorInfoList = [];
        importInstance.visible = false;
        importInstance.previewData = {};
      };
    };
    app.config.globalProperties.$import = importExcel;
    window.$import = importExcel;
  },
};
